package org.jeik.lifeCycle;


import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;

import org.jeik.controllers.NavigationController;
import org.jeik.controllers.NavigationRule;
import org.jeik.utils.Log;

/**
 * This class will wrap the actual Lifecycle and intercept the
 * thrown or unhandled exception, log it and then redirect client to error page.
 *
 * @auther AAsha
 */
public class InterceptingLifecycle extends Lifecycle {

    private Lifecycle wrapped;

    /**
     *
     * @param standardLifecycle
     */
    public InterceptingLifecycle(Lifecycle standardLifecycle) {
        wrapped = standardLifecycle;
    }

    /**
     *
     * @return
     */
    Lifecycle getWrapped() {
        return wrapped;
    }

    /**
     *
     * @param listener
     */
    @Override
    public void addPhaseListener(PhaseListener listener) {
        getWrapped().addPhaseListener(listener);
    }

    /**
     *
     * @param context
     * @throws FacesException
     */
    @Override
    public void execute(FacesContext context) {
        try {
            getWrapped().execute(context);
        } catch (Throwable t) {
            Log.error(this, t.getMessage(), t);
            NavigationController.navigate(NavigationRule.ERROR_PAGE);
        }
    }

    /**
     *
     * @param context
     * @throws FacesException
     */
    @Override
    public void render(FacesContext context) throws FacesException {
      try {
        getWrapped().render(context);
      } catch (FacesException t) {
    	  Log.error(this, t.getMessage(), t);
          NavigationController.navigate(NavigationRule.ERROR_PAGE);
      }
    }

    /**
     *
     * @return
     */
    @Override
    public PhaseListener[] getPhaseListeners() {
        return getWrapped().getPhaseListeners();
    }

    /**
     *
     * @param listener
     */
    @Override
    public void removePhaseListener(PhaseListener listener) {
        getWrapped().removePhaseListener(listener);
    }
    
}
